package com.agileai.miscdp.hotweb.ui.actions;

import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;

import com.agileai.miscdp.hotweb.ConsoleHandler;
import com.agileai.miscdp.hotweb.domain.ProjectConfig;
import com.agileai.miscdp.server.HotServerManage;
import com.agileai.miscdp.util.MiscdpUtil;

public class LoadAppAction implements IObjectActionDelegate{
    private IWorkbenchPart targetPart;  
    
	public void run(IAction action) {
		ISelection selection = targetPart.getSite().getSelectionProvider().getSelection();
		IStructuredSelection curSelection = (IStructuredSelection)selection;
		IJavaProject javaProject = (IJavaProject)curSelection.getFirstElement();
		String appName = javaProject.getProject().getName();
		ConsoleHandler.info("loading application <" + appName + ">....");
		
		ProjectConfig projectConfig = MiscdpUtil.getProjectConfig(appName);
		
		String serverAddress = projectConfig.getServerAddress();
		String serverPort = projectConfig.getServerPort();
		try {
			String docBase = javaProject.getProject().getLocation().toString()+"/WebRoot";
			HotServerManage hotServerManage = MiscdpUtil.getHotServerManage(serverAddress, serverPort);
			boolean isIntegrateApp = projectConfig.isIntegrateWebProject();
			boolean result = hotServerManage.createContext(appName, docBase,isIntegrateApp);
			if (result){
				ConsoleHandler.info("load application <" + appName + "> sucessfully !");				
			}else{
				ConsoleHandler.info("load application <" + appName + "> error !!");
			}
		} catch (Exception e) {
			ConsoleHandler.error(e.getLocalizedMessage());
		}
	}

	public void setActivePart(IAction action, IWorkbenchPart workbenchPart) {
        this.targetPart = workbenchPart;  
	}
	public void selectionChanged(IAction action, ISelection selection) {
	}	
}